﻿Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design

Namespace System.Workflow.ComponentModel.Design
    Friend NotInheritable Class ComponentChangeDispatcher
        Implements IDisposable
        ' Methods
        Public Sub New(ByVal serviceProvider As IServiceProvider, ByVal component As Object, ByVal propertyDescriptor As PropertyDescriptor)
            Me.serviceProvider = serviceProvider
            Me.component = component
            Me.property = propertyDescriptor
            Dim service As IComponentChangeService = [TryCast](serviceProvider.GetService(GetType(IComponentChangeService)),IComponentChangeService)
            If (Not service Is Nothing) Then
                Try 
                    Me.newValue = Me.oldValue = propertyDescriptor.GetValue(component)
                    propertyDescriptor.AddValueChanged(component, New EventHandler(AddressOf Me.OnValueChanged))
                    service.OnComponentChanging(component, propertyDescriptor)
                Catch exception As CheckoutException
                    If (Not exception Is CheckoutException.Canceled) Then
                        Throw exception
                    End If
                End Try
            End If
        End Sub

        Public Sub Dispose()
            Dim service As IComponentChangeService = [TryCast](Me.serviceProvider.GetService(GetType(IComponentChangeService)),IComponentChangeService)
            If (Not service Is Nothing) Then
                service.OnComponentChanged(Me.component, Me.property, Me.oldValue, Me.newValue)
            End If
        End Sub

        Private Sub OnValueChanged(ByVal sender As Object, ByVal e As EventArgs)
            Me.newValue = Me.property.GetValue(Me.component)
            Me.property.RemoveValueChanged(Me.component, New EventHandler(AddressOf Me.OnValueChanged))
        End Sub


        ' Fields
        Private component As Object
        Private newValue As Object
        Private oldValue As Object
        Private [property] As PropertyDescriptor
        Private serviceProvider As IServiceProvider
    End Class
End Namespace

